package com.atguigu.lease.web.admin.service.impl;

import com.atguigu.lease.common.globalException.LeaseException;
import com.atguigu.lease.common.properties.JwtProperties;
import com.atguigu.lease.common.result.ResultCodeEnum;
import com.atguigu.lease.common.utils.JwtUtil;
import com.atguigu.lease.model.entity.SystemUser;
import com.atguigu.lease.model.enums.BaseStatus;
import com.atguigu.lease.web.admin.service.LoginService;
import com.atguigu.lease.web.admin.service.SystemUserService;
import com.atguigu.lease.web.admin.vo.login.CaptchaVo;
import com.atguigu.lease.web.admin.vo.login.LoginVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.wf.captcha.SpecCaptcha;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class LoginServiceImpl implements LoginService {
    @Autowired
    private RedisTemplate<String,Object> redisTemplate;
    @Autowired
    private SystemUserService systemUserService;
    @Autowired
    private JwtProperties jwtProperties;


    //获取验证码
    public CaptchaVo getCaptcha() {
        //创建验证码
        SpecCaptcha specCaptcha = new SpecCaptcha(130, 48,4);

        //获取验证码
        String code = specCaptcha.text().toLowerCase();

        //生成一个key，要求前缀是admin:login:
        String key = "admin:login:"+ UUID.randomUUID();

        //将验证码保存到redis中
        redisTemplate.opsForValue().set(key,code,60, TimeUnit.SECONDS);

        return new CaptchaVo(specCaptcha.toBase64(),key);
    }


    //登录
    public String login(LoginVo loginVo) {
        //1.判断是否有captchaCode
        if(loginVo.getCaptchaCode() == null){
            throw new LeaseException(ResultCodeEnum.APP_LOGIN_CODE_EMPTY);
        }

        //2.判断验证码是否过期
        String code = redisTemplate.opsForValue().get(loginVo.getCaptchaKey()).toString();
        if(code == null){
            throw new LeaseException(ResultCodeEnum.ADMIN_CAPTCHA_CODE_EXPIRED);
        }

        //3.判断验证码是否正确
        if(!code.equalsIgnoreCase(loginVo.getCaptchaCode())){
            throw new LeaseException(ResultCodeEnum.APP_LOGIN_CODE_ERROR);
        }

        //4.根据用户名查询用户
        LambdaQueryWrapper<SystemUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SystemUser::getUsername, loginVo.getUsername());
        SystemUser systemUser = systemUserService.getOne(queryWrapper);
        //判断用户是否存在
        if(systemUser == null){
            throw new LeaseException(ResultCodeEnum.ADMIN_ACCOUNT_NOT_EXIST_ERROR);
        }

        //5.判断用户状态是否为禁用
        if(systemUser.getStatus() == BaseStatus.DISABLE){
            throw new LeaseException(ResultCodeEnum.ADMIN_ACCOUNT_DISABLED_ERROR);
        }

        //6.验证密码是否正确
        String password = DigestUtils.md5Hex(loginVo.getPassword());//获取输入的密码并进行MD5加密
        if(!password.equals(systemUser.getPassword())){
            throw new LeaseException(ResultCodeEnum.ADMIN_ACCOUNT_ERROR);
        }

        //创建jwt令牌
        Map<String, Object> claims = new HashMap<>();
        claims.put("userId", systemUser.getId());
        claims.put("userName", systemUser.getUsername());
        String token = JwtUtil.createJwt(jwtProperties.getAdminSecretKey(), jwtProperties.getAdminTtl(), claims);
        return token;
    }
}
